<?php

/**
 *    商品管理类
 *
 *    @author  yanghj 2014-07-23
 *    @version 1.0 
 */
define('THUMB_WIDTH', 400);
define('THUMB_HEIGHT', 400);
define('MOBILE_THUMB_WIDTH', 200);
define('MOBILE_THUMB_HEIGHT', 200);
define('THUMB_QUALITY', 85);

/* 品牌申请状态 */
define('BRAND_PASSED', 1);
define('BRAND_REFUSE', 0);

/* 商品管理控制器 */

class My_goodsApp extends StoreadminbaseApp
{

    var $_goods_mod;
    var $_goodsspec_mod;
    var $_image_mod;
    var $_uploadedfile_mod;
    var $_store_id;
    var $_brand_mod;
    var $_last_update_id;
    var $_gcategory_mod;
    var $_attribute_mod;
    var $spec_mod;
    var $attr_mod;
    var $shipping_mod;
    var $volumeprice_mod;
    var $_sgrade;

    /* 构造函数 */

    function __construct()
    {
        $this->My_goodsApp();
    }

    function My_goodsApp()
    {
        parent::__construct();

        $this->_store_id = intval($this->visitor->get('manage_store'));
        $this->_goods_mod = & bm('goods', array('_store_id' => $this->_store_id));
        $this->_goodsspec_mod = & m('goodsspec');
        $this->_image_mod = & m('goodsimage');
        $this->_uploadedfile_mod = & m('uploadedfile');
        $this->_brand_mod = & m('brand');
        $this->_gcategory_mod = & bm('gcategory', array('_store_id' => 0));
        $this->_attribute_mod = & m('attribute');
        $this->spec_mod = & m('spec');
        $this->attr_mod = & m('goodsattr');
        $this->shipping_mod = & m('shipping');
        $this->volumeprice_mod = & m('volumeprice');
        $this->_sgrade = intval($this->visitor->get('sgrade'));
    }

    function index()
    {

        /* 取得店铺商品分类 */
        $this->assign('sgcategories', $this->_get_sgcategory_options());
        $this->assign('goodcategories', $this->_gcategory_mod->get_list(0));
        $this->assign('parents', $this->_get_options());
        $conditions = $this->_get_conditions();
        $page = $this->_get_page();
        $page_nolimit = array();
        $goods_list = $this->_get_goods($conditions, $page);
        $all_goods = $this->_get_goods($conditions, $page_nolimit);
        require(ROOT_PATH . '/api/adv.inc.php');
        foreach ($goods_list as $key => $goods)
        {
            $goods_list[$key]['cate_name'] = nl2br($this->_goods_mod->format_cate_name($goods['cate_name']));
            $goods_list[$key]['good_status'] = $goods_data[$goods['if_show']];
            $goods_list[$key]['price'] = $this->_goods_mod->get_price_interval($goods['goods_id'], $goods['price_type']);
        }
        $this->assign('goods_list', $goods_list);
        $page['item_count'] = $this->_goods_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->assign('order', $order);
        $this->assign('sort', $sort);
        $this->import_resource(array(
            'script' => array(
                array(
                    'path' => 'dialog/dialog.js',
                    'attr' => 'id="dialog_js" charset="utf-8"',
                ),
                array(
                    'path' => 'jquery.ui/jquery.ui.js',
                    'attr' => 'charset="utf-8"',
                ),
                array(
                    'path' => 'jquery.plugins/jquery.validate.js',
                    'attr' => 'charset="utf-8"',
                ),
                array(
                    'path' => 'utils.js',
                    'attr' => 'charset="utf-8"',
                ),
            ),
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css',
        ));

        //vdump($goods_list);
        /* 当前用户中心菜单 */
        switch ($_GET['character'])
        {
            case 'show':
                $this->_curitem('my_goods_sell');
                $lg = LANG::get('show');
                break;
            case 'hide':
                $this->_curitem('my_goods_await');
                $lg = LANG::get('hide');
                break;
            case 'closed':
                $this->_curitem('my_goods_drops');
                $lg = LANG::get('close');
                break;
            default:
                $this->_curitem('my_goods_all');
                $lg = LANG::get('my_goods_all');
        }
        $this->_curmenu('goods_list');
        /* 当前页面信息 */
        $this->_curlocal(LANG::get('seller_center'), 'index.php?app=seller', LANG::get('my_goods'), 'index.php?app=my_goods', $lg);
        //$this->import_resource(array('script' => 'utils.js'));
        $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('my_goods'));
        $this->assign('goods_ids', implode(',', array_keys($all_goods)));
        $store_mod = & m('store');
        $store = $store_mod->get_info($this->_store_id);
        $this->assign('store', $store);
        $this->assign('show_edit_stock', OPEN_STORE_PRIV);
        $this->assign('gets', $_GET);
        //echo'<pre>';

        $this->display('my_goods.index.html');
    }

    function truncate()
    {
        $id = isset($_POST['goods_ids']) ? trim($_POST['goods_ids']) : '';
        if (!$id)
        {
            $this->show_warning('no_goods_to_drop');
            return;
        }

        $ids = explode(',', $id);
        $this->_goods_mod->drop_data($ids);
        $rows = $this->_goods_mod->drop($ids);
        if ($this->_goods_mod->has_error())
        {
            $this->show_warning($this->_goods_mod->get_error());
            return;
        }

        $this->show_message(sprintf(Lang::get('truncate_ok'), $rows), 'back_list', 'index.php?app=my_goods'
        );
    }

    function _get_goods($conditions, &$page)
    {
        if (intval($_GET['goodsCategory']) > 0)
        {
            $cate_mod = & bm('gcategory', array('_store_id' => $this->_store_id));
            $cate_ids = $cate_mod->get_descendant_ids(intval($_GET['goodsCategory']));
        }
        else
        {
            $cate_ids = 0;
        }

        // 标识有没有过滤条件
        if ($conditions != '1 = 1' || !empty($_GET['goodsCategory']))
        {
            $this->assign('filtered', 1);
        }

        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order, array('asc', 'desc')))
            {
                $sort = 'goods_id';
                $order = 'desc';
            }
        }
        else
        {
            $sort = 'goods_id';
            $order = 'desc';
        }

        if ($page)
        {
            $limit = $page['limit'];
            $count = true;
        }
        else
        {
            $limit = '';
            $count = false;
        }

        /* 取得商品列表 */
        $goods_list = $this->_goods_mod->get_list(array(
            'conditions' => $conditions,
            'count' => $count,
            'order' => "$sort $order",
            'limit' => $limit,
            ), $cate_ids);

        return $goods_list;
    }

    function _get_conditions()
    {
        /* 搜索条件 */

        $conditions = "1 = 1";
        if (trim($_GET['goodsName']))
        {
            $conditions .= " AND goods_name LIKE '%" . html_script($_GET['goodsName']) . "%' ";
        }
        if (trim($_GET['goodsNum']))
        {
            $conditions .= " AND gs.sku LIKE '%" . html_script($_GET['goodsNum']) . "%' ";
        }

        if (intval($_GET['goodsId']))
        {
            $conditions .= " AND g.goods_id = ".intval($_GET['goodsId']);
        }

        /* 价格查询 */
        if ($_GET['priceFrom'] or $_GET['priceTo'])
        {
            $min_price = abs(floatval($_GET['priceFrom']));
            $max_price = abs(floatval($_GET['priceTo']));
            $min_price > 0 && $conditions .= " AND g.price >= '$min_price'";
            $max_price > 0 && $conditions .= " AND g.price <= '$max_price'";
        }

        /* 销量查询 */
        if ($_GET['saleFrom'] or $_GET['saleTo'])
        {
            $min_sale = intval($_GET['saleFrom']);
            $max_sale = intval($_GET['saleTo']);
            $min_sale > 0 && $conditions .= " AND sales >= '$min_sale'";
            $max_sale > 0 && $conditions .= " AND sales <= '$max_sale'";
        }

        if (intval($_GET['goodsmenu']))
        {
            $conditions .= " AND (g.Cate_id_1='" . intval($_GET['goodsmenu']) . "' or g.Cate_id_2='" . intval($_GET['goodsmenu']) . "' or g.Cate_id_3='" . intval($_GET['goodsmenu']) . "' or g.Cate_id_4='" . intval($_GET['goodsmenu']) . "')";
        }
        if ($_GET['character'])
        {
            switch ($_GET['character'])
            {
                case 'show':
                    $conditions .= " AND if_show = 1";
                    break;
                case 'hide':
                    $conditions .= " AND if_show = 0";
                    break;
                case 'closed':
                    $conditions .= " AND if_show = 2";
                    break;
                /* case 'recommended':
                  $conditions .= " AND g.recommended = 1";
                  break; */
            }
        }

        return $conditions;
    }

    function batch_edit()
    {
        if (!IS_POST)
        {
            /* 取得商品分类 */
            $this->assign('mgcategories', $this->_get_mgcategory_options(0)); // 商城分类第一级
            $this->assign('sgcategories', $this->_get_sgcategory_options());  // 店铺分类

            /* 当前页面信息 */
            $this->_curlocal(LANG::get('seller_center'), 'index.php?app=seller', LANG::get('my_goods'), 'index.php?app=my_goods', LANG::get('goods_add'));
            $this->_curitem('my_goods');
            $this->_curmenu('batch_edit');
            $this->_config_seo('title', Lang::get('seller_center') . Lang::get('my_goods'));

            $this->headtag('<script type="text/javascript" src="{lib file=mlselection.js}"></script>');
            $this->import_resource(array(
                'script' => array(
                    array(
                        'path' => 'jquery.plugins/jquery.validate.js',
                        'attr' => 'charset="utf-8"',
                    ),
                ),
            ));
            $this->display('my_goods.batch.html');
        }
        else
        {
            $id = isset($_POST['id']) ? trim($_POST['id']) : '';
            if (!$id)
            {
                $this->show_warning('Hacking Attempt');
                return;
            }

            $ids = explode(',', $id);
            $ids = $this->_goods_mod->get_filtered_ids($ids); // 过滤掉非本店goods_id
            // edit goods

            $data = array();
            /*if ($_POST['cate_id'] > 0)
            {
                if (!$this->_check_mgcate($_POST['cate_id']))
                {
                    $this->show_warning('select_leaf_category');
                    return;
                }
                $data['cate_id'] = $_POST['cate_id'];
                $data['cate_name'] = $_POST['cate_name'];
            }

            if (trim($_POST['brand']))
            {
                $data['brand'] = trim($_POST['brand']);
            }*/
            $conditions = "goods_id" . db_create_in($ids);
            if ($_POST['if_show'] >= 0)
            {
                $data['if_show'] = $_POST['if_show'] ? intval($_POST['if_show']) : 0;
                if($data['if_show'] == 2)
                {
                    $conditions .=" AND if_show = 1";
                }
            }
            if ($_POST['recommended'] >= 0)
            {
                $data['recommended'] = $_POST['recommended'] ? 1 : 0;
            }
            if ($data)
            {
                $this->_goods_mod->edit($conditions, $data);
            }

            // edit category_goods
            $cate_ids = array();
            foreach ($_POST['sgcate_id'] as $cate_id)
            {
                if ($cate_id)
                {
                    $cate_ids[] = intval($cate_id);
                }
            }
            $cate_ids = array_unique($cate_ids);
            if (!empty($cate_ids))
            {
                foreach ($ids as $goods_id)
                {
                    $this->_goods_mod->unlinkRelation('belongs_to_gcategory', $goods_id);
                    $this->_goods_mod->createRelation('belongs_to_gcategory', $goods_id, $cate_ids);
                }
            }
            // edit goods_spec
            /* = "";
            if ($_POST['price_change'])
            {
                $delta_price = $this->_filter_price($_POST['price']); // 价格变化量
                switch ($_POST['price_change'])
                {
                    case 'change_to':
                        $sql .= "price = '" . $delta_price . "'";
                        break;
                    case 'inc_by':
                        $sql .= "price = price + '" . $delta_price . "'";
                        break;
                    case 'dec_by':

                        $sql .= "price = IF((price - '" . $delta_price . "') <0 , 0, price - '" . $delta_price . "')";
                        break;
                }
            }
            if ($sql)
            {
                $this->_goodsspec_mod->edit("goods_id" . db_create_in($ids), $sql);
                $this->_goods_mod->edit($ids, $sql);
            }

            $sql = "";
            if ($_POST['stock_change'])
            {
                $delta_stock = intval($_POST['stock']); // 库存变化量
                switch ($_POST['stock_change'])
                {
                    case 'change_to':
                        $sql .= "stock = '" . $delta_stock . "'";
                        break;
                    case 'inc_by':
                        $sql .= "stock = stock + '" . $delta_stock . "'";
                        break;
                    case 'dec_by':
                        $sql .= "stock = IF((stock - '" . $delta_stock . "') <0 , 0, stock - '" . $delta_stock . "')";
                        break;
                }
            }
            if ($sql)
            {
                $this->_goodsspec_mod->edit("goods_id" . db_create_in($ids), $sql);
            }*/

            $ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
            $this->show_message('edit_ok', 'back_list', 'index.php?app=my_goods&page=' . $ret_page);
        }
    }

    /* 检查商品分类：添加、编辑商品表单验证时用到 */

    function check_mgcate()
    {
        $cate_id = isset($_GET['cate_id']) ? intval($_GET['cate_id']) : 0;

        echo ecm_json_encode($this->_check_mgcate($cate_id));
    }

    /**
     * 检查商品分类（必选，且是叶子结点）
     *
     * @param   int     $cate_id    商品分类id
     * @return  bool
     */
    function _check_mgcate($cate_id)
    {
        if ($cate_id > 0)
        {
            $gcategory_mod = & bm('gcategory');
            $info = $gcategory_mod->get_info($cate_id);
            if ($info && $info['if_show'] && $gcategory_mod->is_leaf($cate_id))
            {
                return true;
            }
        }

        return false;
    }

    function add()
    {
        /* 检测支付方式、配送方式、商品数量等 */
        if (!$this->_addible())
        {
            return;
        }
        $sgcategories = $this->_get_sgcategory_options(); //店铺分类
        if (!$sgcategories)
        {
            $this->show_warning('请先创建店铺商品分类', '去创建', 'index.php?app=my_category');
            return;
        }

        if (!IS_POST)
        {
            include(ROOT_PATH . '/includes/cfg_status.php');
            /* 添加传给iframe空的id,belong */
            $this->assign("id", 0);
            $this->assign("belong", BELONG_GOODS);
            $this->assign('goods', $this->_get_goods_info(0));
            //获取运费模板
            $sv = $this->shipping_mod->get_shipping_list($this->_store_id);
            $shipping = array();
            foreach ($sv as $k => $v)
            {
                $shipping[$k]['shipping_name'] = $v['shipping_name'];
                $shipping[$k]['shipping_id'] = $v['shipping_id'];
            }
            $this->assign('shipping', $shipping);

            /* 取得游离状的图片 */
            $goods_images = array();
            $desc_images = array();
            $uploadfiles = $this->_uploadedfile_mod->find(array(
                'join' => 'belongs_to_goodsimage',
                'conditions' => "belong=" . BELONG_GOODS . " AND item_id=0 AND store_id=" . $this->_store_id,
                'order' => 'add_time ASC'
            ));
            foreach ($uploadfiles as $key => $uploadfile)
            {
                if ($uploadfile['goods_id'] == null)
                {
                    $desc_images[$key] = $uploadfile;
                }
                else
                {
                    $goods_images[$key] = $uploadfile;
                }
            }

            $this->assign('goods_images', $goods_images);
            $this->assign('desc_images', $desc_images);
            /* 取得商品分类 */
            $this->assign('mgcategories', $this->_get_mgcategory_options(0)); // 商城分类第一级
            $this->assign('sgcategories', $sgcategories);  // 店铺分类
            $this->assign('shipping_type', $cfg_shipping_type);
            $this->assign('shipping_time', $cfg_shipping_time);
            $this->assign('goods_units', $cfg_goods_units);

            /* 当前页面信息 */
            $this->_curlocal(LANG::get('seller_center'), 'index.php?app=seller', LANG::get('my_goods'), 'index.php?app=my_goods', LANG::get('goods_add'));
            $this->_curitem('my_goods');
            $this->_curmenu('goods_add');
            $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('goods_add'));

            /* 商品图片批量上传器 */
            $this->assign('images_upload', $this->_build_upload(array(
                    'obj' => 'GOODS_SWFU',
                    'belong' => BELONG_GOODS,
                    'item_id' => 0,
                    'button_text' => Lang::get('bat_upload'),
                    'progress_id' => 'goods_upload_progress',
                    'upload_url' => 'index.php?app=swfupload&instance=goods_image&xs=1',
                    'if_multirow' => 1,
            )));

            /* 编辑器图片批量上传器 */
            $this->assign('editor_upload', $this->_build_upload(array(
                    'obj' => 'EDITOR_SWFU',
                    'belong' => BELONG_GOODS,
                    'item_id' => 0,
                    'button_text' => Lang::get('bat_upload'),
                    'button_id' => 'editor_upload_button',
                    'progress_id' => 'editor_upload_progress',
                    'upload_url' => 'index.php?app=swfupload&instance=desc_image',
                    'if_multirow' => 1,
                    'ext_js' => false,
                    'ext_css' => false,
            )));

            $this->import_resource(array(
                'script' => array(
                    array(
                        'path' => 'jquery.plugins/jquery.validate.js',
                        'attr' => 'charset="utf-8"',
                    ),
                    array(
                        'path' => 'jquery.plugins/jquery.metadata.js',
                        'attr' => 'charset="utf-8"',
                    ),
                    array(
                        'path' => 'jquery.ui/jquery.ui.js',
                        'attr' => 'charset="utf-8"',
                    ),
                    array(
                        'attr' => 'id="dialog_js" charset="utf-8"',
                        'path' => 'dialog/dialog.js',
                    ),
                ),
                'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css',
            ));
            //var_dump($this->_get_goods_info(0));
            $this->_curitem('my_goods_add');
            /* 所见即所得编辑器 */
            extract($this->_get_theme());
            $this->assign('build_editor', $this->_build_editor(array(
                    'name' => 'description',
                    'content_css' => SITE_URL . "/themes/store/{$template_name}/styles/{$style_name}" . '/shop.css', // for preview
            )));
            if($this->_sgrade == 1){
                $this->display('my_goods.form.html');
            }else{
                $this->display('my_goods_commission.form.html');
            }
            
        }
        else
        {
            /* 取得数据 */
            //vdump($_POST);
            $data = $this->_get_post_data(0);
            /* 检查数据 */
            if (!$this->_check_post_data($data, 0))
            {
                $this->show_warning($this->get_error());
                return;
            }
            /* 保存数据 */
            if (!$this->_save_post_data($data, 0))
            {
                $this->show_warning($this->get_error());
                return;
            }
            $goods_info = $this->_get_goods_info($this->_last_update_id);
            if ($goods_info['if_show'])
            {
                $goods_url = SITE_URL . '/' . url('app=goods&id=' . $goods_info['goods_id']);
                $feed_images = array();
                $feed_images[] = array(
                    'url' => SITE_URL . '/' . $goods_info['default_image'],
                    'link' => $goods_url,
                );
                $this->send_feed('goods_created', array(
                    'user_id' => $this->visitor->get('user_id'),
                    'user_name' => $this->visitor->get('user_name'),
                    'goods_url' => $goods_url,
                    'goods_name' => $goods_info['goods_name'],
                    'images' => $feed_images
                ));
            }

            $this->show_message('add_ok', 'back_list', 'index.php?app=my_goods', 'continue_add', 'index.php?app=my_goods&amp;act=add'
            );
        }
    }

    function edit()
    {
        include(ROOT_PATH . '/includes/cfg_status.php');
        import('image.func');
        import('uploader.lib');
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        if (!IS_POST)
        {
            /* 传给iframe id */
            $this->assign('id', $id);
            $this->assign('belong', BELONG_GOODS);
            if (!$id || !($goods = $this->_get_goods_info($id)))
            {
                $this->show_warning('no_such_goods');
                return;
            }
            $goods['tags'] = trim($goods['tags'], ',');

            //获取运费模板
            $sv = $this->shipping_mod->get_shipping_list($this->_store_id);
            $shipping = array();
            foreach ($sv as $k => $v)
            {
                $shipping[$k]['shipping_name'] = $v['shipping_name'];
                $shipping[$k]['shipping_id'] = $v['shipping_id'];
                if ($goods['shipping_id'] > 0 && $v['shipping_id'] == $goods['shipping_id'])
                {
                    $goods['shipping_compute_mode'] = $v['compute_mode'];
                }
            }
            $this->assign('shipping', $shipping);

            /* 判断是否最后一级分类 */
            $is_last_cate = $this->_check_mgcate($goods['cate_id']);
            if ($is_last_cate)
            {
                $attr_list = $this->_get_html_attribute($goods['cate_id'], $goods['goods_id']); //获取属性
                $spec_list = $this->_get_html_spec($goods['cate_id'], $goods['goods_id']); //获取规格          
            }
            if ($goods['_specs'])
            {
                foreach ($goods['_specs'] as $key => $val)
                {
                    $goods['stock'] += $val['stock'];
                    $spec[$val['spec_1']][$key] = $val;
                }
                sort($spec);
                $goods['_specs_2'] = $spec;
            }
            $this->assign('attr_list', $attr_list);
            $this->assign('spec_list', $spec_list);
            $this->assign('goods', $goods);

            /* 取到商品关联的图片 */
            $uploadedfiles = $this->_uploadedfile_mod->find(array(
                'fields' => "f.*,goods_image.*",
                'conditions' => "store_id=" . $this->_store_id . " AND belong=" . BELONG_GOODS . " AND item_id=" . $id,
                'join' => 'belongs_to_goodsimage',
                'order' => 'add_time ASC'
            ));
            $default_goods_images = array(); // 默认商品图片
            $other_goods_images = array(); // 其他商品图片
            $desc_images = array(); // 描述图片
            /* if (!empty($goods['default_image']))
              {
              $goods_images
              } */
            foreach ($uploadedfiles as $key => $uploadedfile)
            {
                if ($uploadedfile['goods_id'] == null)
                {
                    $desc_images[$key] = $uploadedfile;
                }
                else
                {
                    if (!empty($goods['default_image']) && ($uploadedfile['thumbnail'] == $goods['default_image']))
                    {
                        $default_goods_images[$key] = $uploadedfile;
                    }
                    else
                    {
                        $other_goods_images[$key] = $uploadedfile;
                    }
                }
            }

            $this->assign('goods_images', array_merge($default_goods_images, $other_goods_images));
            $this->assign('desc_images', $desc_images);
            $this->assign('shipping_type', $cfg_shipping_type);
            $this->assign('shipping_time', $cfg_shipping_time);
            $this->assign('goods_units', $cfg_goods_units);

            /* 取得商品分类 */
            $this->assign('mgcategories', $this->_get_mgcategory_options(0)); // 商城分类第一级
            $this->assign('sgcategories', $this->_get_sgcategory_options());  // 店铺分类

            /* 当前页面信息 */
            $this->_curlocal(LANG::get('seller_center'), 'index.php?app=seller', LANG::get('my_goods'), 'index.php?app=my_goods', LANG::get('goods_edit'));
            $this->_curitem('my_goods_all');
            $this->_curmenu('edit_goods');
            $this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('edit_goods'));
            $this->import_resource(array(
                'script' => array(
                    array(
                        'path' => 'jquery.plugins/jquery.validate.js',
                        'attr' => 'charset="utf-8"',
                    ),
                    array(
                        'path' => 'jquery.plugins/jquery.metadata.js',
                        'attr' => 'charset="utf-8"',
                    ),
                    array(
                        'path' => 'jquery.ui/jquery.ui.js',
                        'attr' => 'charset="utf-8"',
                    ),
                    array(
                        'attr' => 'id="dialog_js" charset="utf-8"',
                        'path' => 'dialog/dialog.js',
                    ),
                ),
                'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css',
            ));


            /* 商品图片批量上传器 */
            $this->assign('images_upload', $this->_build_upload(array(
                    'obj' => 'GOODS_SWFU',
                    'belong' => BELONG_GOODS,
                    'item_id' => $id,
                    'button_text' => Lang::get('bat_upload'),
                    'progress_id' => 'goods_upload_progress',
                    'upload_url' => 'index.php?app=swfupload&instance=goods_image&xs=1',
                    'if_multirow' => 1,
            )));

            /* 编辑器图片批量上传器 */
            $this->assign('editor_upload', $this->_build_upload(array(
                    'obj' => 'EDITOR_SWFU',
                    'belong' => BELONG_GOODS,
                    'item_id' => $id,
                    'button_text' => Lang::get('bat_upload'),
                    'button_id' => 'editor_upload_button',
                    'progress_id' => 'editor_upload_progress',
                    'upload_url' => 'index.php?app=swfupload&instance=desc_image',
                    'if_multirow' => 1,
                    'ext_js' => false,
                    'ext_css' => false,
            )));

            /* 所见即所得编辑器 */
            extract($this->_get_theme());
            $this->assign('build_editor', $this->_build_editor(array(
                    'name' => 'description',
                    'content_css' => SITE_URL . "/themes/store/{$template_name}/styles/{$style_name}" . '/shop.css', // for preview
            )));
            if($this->_sgrade == 1){
                $this->display('my_goods_edit.form.html');
            }else{
                $this->display('my_goods_edit_commission.form.html');
            }
            
        }
        ///编辑产品入库处理
        else
        {
            /* 取得数据 */
            $data = $this->_get_post_data($id);

            /* 检查数据 */
            if (!$this->_check_post_data($data, $id))
            {
                $this->show_warning($this->get_error());
                return;
            }

            /* 保存商品 */
            if (!$this->_save_post_data($data, $id))
            {
                $this->show_warning($this->get_error());
                return;
            }

            $this->show_message('edit_ok', 'back_list', 'index.php?app=my_goods', 'edit_again', 'index.php?app=my_goods&amp;act=edit&amp;id=' . $id);
        }
    }

    function edit_stock()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        $page = empty($_GET['page']) ? 0 : intval($_GET['page']);
        if (!IS_POST)
        {
            if (!$id || !($goods = $this->_get_goods_info($id)))
            {
                $this->pop_warning('no_such_goods');
                return;
            }

            if ($goods['_specs'])
            {
                foreach ($goods['_specs'] as $key => $val)
                {
                    $goods['stock'] += $val['stock'];
                    $spec[$val['spec_1']][$key] = $val;
                }
                sort($spec);
                $goods['_specs_2'] = $spec;
            }
            
            $this->assign('goods', $goods);

            $this->display('my_goods_edit_stock.html');
        }
        else
        {
            $spec_name_1 = !empty($_POST['spec_name_1']) && !empty($_POST['spec_1']) ? html_script(trim($_POST['spec_name_1'])) : '';
            $spec_name_2 = !empty($_POST['spec_name_2']) && !empty($_POST['spec_2']) ? html_script(trim($_POST['spec_name_2'])) : '';

            if ($spec_name_1 && $spec_name_2)
            {
                $goods['spec_qty'] = 2;
            }
            elseif ($spec_name_1 || $spec_name_2)
            {
                $goods['spec_qty'] = 1;
            }
            else
            {
                $goods['spec_qty'] = 0;
            }

            $specs = array(); // 原始规格       
            switch ($goods['spec_qty'])
            {
                case 0: // 没有规格
                    $specs[intval($_POST['spec_id'])] = array(
                        'stock' => intval($_POST['totalstock']),
                    );
                    break;
                case 1: // 一个规格
                    $spec_data = $spec_name_1 ? $_POST['spec_1'] : $_POST['spec_2'];

                    foreach ($spec_data as $key => $spec_1)
                    {
                        $spec_1 = trim($spec_1);
                        if ($spec_1)
                        {
                            if (($spec_id = intval($_POST['spec_id'][$key]))) // 已有规格ID的
                            {
                                $specs[$key] = array(
                                    'stock' => intval($_POST['stock'][$key]),
                                );
                            }
                        }
                    }
                    break;
                case 2: // 二个规格
                    foreach ($_POST['spec_1'] as $key => $spec_1)
                    {
                        $spec_1 = trim($spec_1);
                        $spec_2 = trim($_POST['spec_2'][$key]);
                        if ($spec_1 && $spec_2)
                        {
                            if (($spec_id = intval($_POST['spec_id'][$key]))) // 已有规格ID的
                            {
                                $specs[$key] = array(
                                    'stock' => intval($_POST['stock'][$key]),
                                );
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
            
            foreach ($specs as $key => $spec)
                $this->_goodsspec_mod->edit($key, $spec);
            
            $this->pop_warning("ok", '', 'index.php?app=my_goods&page=' . $page);
        }
    }

    //异步修改数据
    function ajax_col()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        $column = empty($_GET['column']) ? '' : trim($_GET['column']);
        $value = isset($_GET['value']) ? trim($_GET['value']) : '';
        $data = array('goods' => array(),
            'specs' => array(),
            'cates' => array());
        $this->_goods_mod->clear_cache($id);
        if (in_array($column, array('goods_name', 'description', 'cate_id', 'cate_name', 'brand', 'spec_qty', 'if_show', 'closed', 'recommended')))
        {
            $data['goods'][$column] = $value;
            $this->_goods_mod->edit($id, $data['goods']);
            if (!$this->_goods_mod->has_error())
            {
                $result = $this->_goods_mod->get_info($id);
                $this->json_result($result[$column]);
                return;
            }
            else
            {
                $this->json_error($this->_goods_mod->get_error());
                return;
            }
        }
        elseif (in_array($column, array('price', 'stock', 'sku')))
        {
            if ($column == 'price')
            {
                $value = $this->_filter_price($value);
            }
            elseif ($column == 'stock')
            {
                $value = intval($value);
            }

            $data['specs'][$column] = $value;
            $this->_goodsspec_mod->edit("goods_id = $id", $data['specs']);
            if (!$this->_goodsspec_mod->has_error())
            {
                $result = $this->_goodsspec_mod->get("goods_id = $id");
                //修改商品表中默认的字段的价格
                if ($column == 'price')
                {
                    $this->_goods_mod->edit($id, $data['specs']);
                }
                $this->json_result($result[$column]);
                return;
            }
            else
            {
                $this->json_error($this->_goodsspec_mod->get_error());
                return;
            }
        }
        else
        {
            $this->json_error('unallow edit');
            return;
        }
    }

    function drop()
    {
        $id = isset($_GET['id']) ? trim($_GET['id']) : '';
        if (!$id)
        {
            $this->show_warning('no_goods_to_drop');
            return;
        }

        $ids = explode(',', $id); //vdump($ids);
        $this->_goods_mod->drop_data($ids);
        $rows = $this->_goods_mod->drop($ids);
        if ($this->_goods_mod->has_error())
        {
            $this->show_warning($this->_goods_mod->get_error());
            return;
        }

        $this->show_message('drop_ok');
    }

    function drop_image()
    {
        import('img_server');
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        $uploadedfile = $this->_uploadedfile_mod->get(array(
            'conditions' => "f.file_id = '$id' AND f.store_id = '{$this->_store_id}'",
            'join' => 'belongs_to_goodsimage',
            'fields' => 'f.file_path, goods_image.image_url, goods_image.thumbnail, goods_image.image_id, f.file_id',
        ));

        if ($uploadedfile)
        {
            $this->_uploadedfile_mod->drop($id);
            if ($this->_image_mod->drop($uploadedfile['image_id']))
            {
                // 删除文件
                $imageUrl = remove_image_server_host($uploadedfile['image_url']);
                $thumbnail = remove_image_server_host($uploadedfile['thumbnail']);
                if (file_exists(ROOT_PATH . '/' . $imageUrl))
                {
                    @unlink(ROOT_PATH . '/' . $imageUrl);
                }
                if (file_exists(ROOT_PATH . '/' . $thumbnail))
                {
                    @unlink(ROOT_PATH . '/' . $thumbnail);
                }
                if (file_exists(ROOT_PATH . '/' . $uploadedfile['file_path']))
                {
                    @unlink(ROOT_PATH . '/' . $uploadedfile['file_path']);
                }

                $this->json_result($id);
                return;
            }
            $this->json_result($id);
            return;
        }
        $this->json_error(Lang::get('no_image_droped'));
    }

    /**
     *  Ajax获取某个分类的属性与规格,返回JSON字符串
     *  @author  yanghj 2014.07.23
     *  @return  JSON字符串
     */
    function AjaxSpecAttr()
    {
        $retval['cate'] = array();
        $retval['attribute'] = '';
        $retval['spec'] = '';
        $cate_id = isset($_GET['cate_id']) ? intval($_GET['cate_id']) : 0;
        if ($cate_id == 0)
        {
            $this->json_error('NO');
            return;
        }
        $mod_gcategory = & m('gcategory');
        $cates = $mod_gcategory->get_list($cate_id, true); //分类的子分类
        if ($cates)
        {
            foreach ($cates as $key => $cate)
            {
                $cates[$key]['cate_name'] = htmlspecialchars($cate['cate_name']);
            }

            $retval['cate'] = array_values($cates);
        }



        /* 判断是否最后一级分类 */
        $is_last_cate = $this->_check_mgcate($cate_id);
        if ($is_last_cate)
        {
            $retval['attribute'] = $this->_get_html_attribute($cate_id); //获取属性
            $retval['spec'] = $this->_get_html_spec($cate_id); //获取规格          
        }

        $this->json_result($retval);
    }

    /* 构造并返回树 */

    function &_tree($gcategories)
    {
        import('tree.lib');
        $tree = new Tree();
        $tree->setTree($gcategories, 'cate_id', 'parent_id', 'cate_name');
        return $tree;
    }

    /* 取得本店所有商品分类 */

    function _get_sgcategory_options()
    {
        $mod = & bm('gcategory', array('_store_id' => $this->_store_id));
        $gcategories = $mod->get_list();
        import('tree.lib');
        $tree = new Tree();
        $tree->setTree($gcategories, 'cate_id', 'parent_id', 'cate_name');
        return $tree->getOptions();
    }

    /* 取得商城商品分类，指定parent_id */

    function _get_mgcategory_options($parent_id = 0)
    {
        $res = array();
        $mod = & bm('gcategory', array('_store_id' => 0));
        $gcategories = $mod->get_list($parent_id, true);
        foreach ($gcategories as $gcategory)
        {
            $res[$gcategory['cate_id']] = $gcategory['cate_name'];
        }
        return $res;
    }

    /**
     * 上传商品图片
     *
     * @param int $goods_id
     * @return bool
     */
    function _upload_image($goods_id)
    { //vdump(111);
        import('image.func');
        import('uploader.lib');
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE);
        $uploader->allowed_size(SIZE_GOODS_IMG); // 500KB

        /* 取得剩余空间（单位：字节），false表示不限制 */
        $store_mod = & m('store');
        $settings = $store_mod->get_settings($this->_store_id);
        $upload_mod = & m('uploadedfile');
        $remain = $settings['space_limit'] > 0 ? $settings['space_limit'] * 1024 * 1024 - $upload_mod->get_file_size($this->_store_id) : false;

        $files = $_FILES['new_file'];
        foreach ($files['error'] as $key => $error)
        {
            if ($error == UPLOAD_ERR_OK)
            {
                /* 处理文件上传 */
                $file = array(
                    'name' => $files['name'][$key],
                    'type' => $files['type'][$key],
                    'tmp_name' => $files['tmp_name'][$key],
                    'size' => $files['size'][$key],
                    'error' => $files['error'][$key]
                );
                $uploader->addFile($file);
                if (!$uploader->file_info())
                {
                    $this->_error($uploader->get_error());
                    return false;
                }

                /* 判断能否上传 */
                if ($remain !== false)
                {
                    if ($remain < $file['size'])
                    {
                        $this->_error('space_limit_arrived');
                        return false;
                    }
                    else
                    {
                        $remain -= $file['size'];
                    }
                }

                $uploader->root_dir(ROOT_PATH);
                $dirname = 'data/files/store_' . $this->_store_id . '/goods_' . (time() % 200);
                $filename = $uploader->random_filename();
                $file_path = $uploader->save($dirname, $filename);
                $thumbnail = dirname($file_path) . '/small_' . basename($file_path);
                make_thumb(ROOT_PATH . '/' . $file_path, ROOT_PATH . '/' . $thumbnail, THUMB_WIDTH, THUMB_HEIGHT, THUMB_QUALITY);

                /* 处理文件入库 */
                $data = array(
                    'store_id' => $this->_store_id,
                    'file_type' => $file['type'],
                    'file_size' => $file['size'],
                    'file_name' => $file['name'],
                    'file_path' => $file_path,
                    'add_time' => gmtime(),
                );
                $uf_mod = & m('uploadedfile');
                $file_id = $uf_mod->add($data);
                if (!$file_id)
                {
                    $this->_error($uf_mod->get_error());
                    return false;
                }

                /* 处理商品图片入库 */
                $data = array(
                    'goods_id' => $goods_id,
                    'image_url' => $file_path,
                    'thumbnail' => $thumbnail,
                    'sort_order' => 255,
                    'file_id' => $file_id,
                );
                if (!$this->_image_mod->add($data))
                {
                    $this->_error($this->_image_mod->get_error());
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 检测店铺是否能添加商品
     *
     */
    function _addible()
    {
        /* $payment_mod =& m('payment');
          $payments = $payment_mod->get_enabled($this->_store_id);
          if (empty($payments))
          {
          $this->show_warning('please_install_payment', 'go_payment', 'index.php?app=my_payment');
          return false;
          } */

        $shipping_mod = & m('shipping');
        $shippings = $shipping_mod->find("store_id = '{$this->_store_id}' AND enabled = 1");
        if (empty($shippings))
        {
            $this->show_warning('please_install_shipping', 'go_shipping', 'index.php?app=my_shipping');
            return false;
        }

        /* 判断商品数是否已超过限制 */
        $store_mod = & m('store');
        $settings = $store_mod->get_settings($this->_store_id);
        if ($settings['goods_limit'] > 0)
        {
            $goods_count = $this->_goods_mod->get_count();
            if ($goods_count >= $settings['goods_limit'])
            {
                $this->show_warning('goods_limit_arrived');
                return false;
            }
        }
        return true;
    }

    /**
     * 保存远程图片
     */
    function _add_remote_image($goods_id)
    {
        foreach ($_POST['new_url'] as $image_url)
        {
            if ($image_url && $image_url != 'http://')
            {
                $data = array(
                    'goods_id' => $goods_id,
                    'image_url' => $image_url,
                    'thumbnail' => $image_url, // 远程图片暂时没有小图
                    'sort_order' => 255,
                    'file_id' => 0,
                );
                if (!$this->_image_mod->add($data))
                {
                    $this->_error($this->_image_mod->get_error());
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 编辑图片
     */
    function _edit_image($goods_id)
    {
        if (isset($_POST['old_order']))
        {
            foreach ($_POST['old_order'] as $image_id => $sort_order)
            {
                $data = array('sort_order' => $sort_order);
                if (isset($_POST['old_url'][$image_id]))
                {
                    $data['image_url'] = $_POST['old_url'][$image_id];
                }
                $this->_image_mod->edit("image_id = '$image_id' AND goods_id = '$goods_id'", $data);
            }
        }

        return true;
    }

    /**
     * 取得商品信息
     */
    function _get_goods_info($id = 0)
    {
        $default_goods_image = Conf::get('default_goods_image'); // 商城默认商品图片
        if ($id > 0)
        {
            $goods_info = $this->_goods_mod->get_info($id); //vdump($goods_info);
            if ($goods_info === false)
            {
                return false;
            }
            $goods_info['default_goods_image'] = $default_goods_image;
            if (empty($goods_info['default_image']))
            {
                $goods_info['default_image'] = $default_goods_image;
            }
        }
        else
        {
            $goods_info = array(
                'cate_id' => 0,
                'if_show' => 1,
                'recommended' => 1,
                'price' => 1,
                'stock' => 1,
                'spec_qty' => 0,
                'spec_name_1' => Lang::get('color'),
                'spec_name_2' => Lang::get('size'),
                'default_goods_image' => $default_goods_image,
            );
        }
        $goods_info['spec_json'] = ecm_json_encode(array(
            'spec_qty' => $goods_info['spec_qty'],
            'price_type' => $goods_info['price_type'],
            'spec_name_1' => isset($goods_info['spec_name_1']) ? $goods_info['spec_name_1'] : '',
            'spec_name_2' => isset($goods_info['spec_name_2']) ? $goods_info['spec_name_2'] : '',
            'specs' => $goods_info['_specs'],
        ));
        return $goods_info;
    }

    /**
     * 提交的数据
     */
    function _get_post_data($id = 0)
    {

        //按数量报价的商品
        if ($_POST['pricetype'] == 1)
        {
            $pricelist_num = $_POST['pricelist_num'];//购买数量
            $pricelist_price = $_POST['pricelist_price'];//商品零售价
            $pricelist_market_price = $_POST['pricelist_market_price'];//商品市场价
            $start_stock = isset($pricelist_num[0]) ? intval($pricelist_num[0]) : '1'; //起订量
            /* 价格区间 */
            $price_arr = array();
            if (is_array($pricelist_num))
            {
                foreach ($pricelist_num as $k => $val)
                {
                    if(empty($pricelist_num[$k]))
                    {
                        continue;
                    }
                    $price_arr[$k]['price_type'] = 1;
                    $price_arr[$k]['volume_number'] = intval($pricelist_num[$k]);
                    $price_arr[$k]['volume_price'] = $this->_filter_price($pricelist_price[$k]);
                    $price_arr[$k]['market_price'] = $this->_filter_price($pricelist_market_price[$k]);
                    $goods_price = $pricelist_price[$k];//商品的价格
                    $goods_market_price = $pricelist_market_price[$k];//商品的市场价格
                }
            }
        }

        //按规格报价的商品
        if ($_POST['pricetype'] == 2)
        {
            $start_stock = isset($_POST['start_num']) ? intval($_POST['start_num']) : '1'; //起订量
            //获取规格最低价
            if (is_array($_POST['price']))
            {
                $format_arr = array_flip($_POST['price']);
                ksort($format_arr);
                $floor_price_key = reset($format_arr);
                $goods_price = key($format_arr);//商品的价格
                $goods_market_price = $_POST['market_price'][$floor_price_key];//商品的市场价格
            }
        }

        $spec_name_1 = !empty($_POST['spec_name_1']) && !empty($_POST['spec_1']) ? html_script(trim($_POST['spec_name_1'])) : '';
        $spec_name_2 = !empty($_POST['spec_name_2']) && !empty($_POST['spec_2']) ? html_script(trim($_POST['spec_name_2'])) : '';
        $goods = array(
            'goods_name' => html_script(trim($_POST['goods_name'])),
            'description' => html_script(trim($_POST['description'])),
            'cate_id' => intval($_POST['cate_id']),
            'cate_name' => html_script(trim($_POST['cate_name'])),
            'brand' => html_script(trim($_POST['brand'])),
            'if_show' => intval($_POST['if_show']),
            'last_update' => gmtime(),
            'recommended' => intval($_POST['recommended']),
            'tags' => html_script(trim($_POST['tags'])),
            'spec_name_1' => $spec_name_1,
            'spec_name_2' => $spec_name_2,
            'shipping_id' => $_POST['shipping_id'] >= 1 ? intval($_POST['shipping_id']) : intval($_POST['freight_pay']),
            'shipping_type' => isset($_POST['delivery_type']) ? intval($_POST['delivery_type']) : 1,
            'shipping_time' => isset($_POST['delivery_time']) ? intval($_POST['delivery_time']) : 1,
            'units' => html_script($_POST['delivery_unit']),
            'price' => $this->_filter_price($goods_price),
            'market_price' => $this->_filter_price($goods_market_price),
            'gweight' => floatval($_POST['gweight']),
            'price_type' => intval($_POST['pricetype']),
            'start_stock' => intval($start_stock),
            'clearing_form' => $this->_sgrade == 2 ? 2 : 1,
            'clearing_price' => $this->_sgrade == 2 ? 0 : $this->_filter_price($_POST['floor_price_num']),
        );

        if ($spec_name_1 && $spec_name_2)
        {
            $goods['spec_qty'] = 2;
        }
        elseif ($spec_name_1 || $spec_name_2)
        {
            $goods['spec_qty'] = 1;
        }
        else
        {
            $goods['spec_qty'] = 0;
        }

        $goods_file_id = array();
        $desc_file_id = array();
        if (isset($_POST['goods_file_id']))
        {
            $goods_file_id = $_POST['goods_file_id'];
        }
        if (isset($_POST['desc_file_id']))
        {
            $desc_file_id = $_POST['desc_file_id'];
        }
        if ($id <= 0)
        {
            $goods['type'] = 'material';
            $goods['closed'] = 0;
            $goods['add_time'] = gmtime();
        }

        $specs = array(); // 原始规格       
        switch ($goods['spec_qty'])
        {
            case 0: // 没有规格
                $specs[intval($_POST['spec_id'])] = array(
                    'price' => $this->_filter_price($_POST['price']),
                    'stock' => intval($_POST['totalstock']),
                    'sku' => html_script(trim($_POST['goods_code'])),
                    'spec_id' => intval($_POST['spec_id']),
                    'market_price' => $this->_filter_price($_POST['market_price']),
                );
                break;
            case 1: // 一个规格
                $spec_data = $spec_name_1 ? $_POST['spec_1'] : $_POST['spec_2'];

                foreach ($spec_data as $key => $spec_1)
                {
                    $spec_1 = trim($spec_1);
                    if ($spec_1)
                    {
                        if (($spec_id = intval($_POST['spec_id'][$key]))) // 已有规格ID的
                        {
                            $specs[$key] = array(
                                'spec_id' => $spec_id,
                                'spec_1' => isset($_POST['spec_1'][$key]) ? trim($_POST['spec_1'][$key]) : '',
                                'spec_2' => isset($_POST['spec_2'][$key]) ? trim($_POST['spec_2'][$key]) : '',
                                'price' => $this->_filter_price($_POST['price'][$key]),
                                'stock' => intval($_POST['stock'][$key]),
                                'sku' => html_script(trim($_POST['sku'][$key])),
                                'base_price' => $this->_filter_price($_POST['floor_price'][$key]),
                                'market_price' => $this->_filter_price($_POST['market_price'][$key]),
                            );
                        }
                        else  // 新增的规格
                        {
                            $specs[$key] = array(
                                'spec_1' => isset($_POST['spec_1'][$key]) ? trim($_POST['spec_1'][$key]) : '',
                                'spec_2' => isset($_POST['spec_2'][$key]) ? trim($_POST['spec_2'][$key]) : '',
                                'price' => $this->_filter_price($_POST['price'][$key]),
                                'stock' => intval($_POST['stock'][$key]),
                                'sku' => html_script(trim($_POST['sku'][$key])),
                                'base_price' => $this->_filter_price($_POST['floor_price'][$key]),
                                'market_price' => $this->_filter_price($_POST['market_price'][$key]),
                            );
                        }
                    }
                }
                break;
            case 2: // 二个规格
                foreach ($_POST['spec_1'] as $key => $spec_1)
                {
                    $spec_1 = trim($spec_1);
                    $spec_2 = trim($_POST['spec_2'][$key]);
                    if ($spec_1 && $spec_2)
                    {
                        if (($spec_id = intval($_POST['spec_id'][$key]))) // 已有规格ID的
                        {
                            $specs[$key] = array(
                                'spec_id' => $spec_id,
                                'spec_1' => $spec_1,
                                'spec_2' => $spec_2,
                                'price' => $this->_filter_price($_POST['price'][$key]),
                                'stock' => intval($_POST['stock'][$key]),
                                'sku' => html_script(trim($_POST['sku'][$key])),
                                'base_price' => $this->_filter_price($_POST['floor_price'][$key]),
                                'market_price' => $this->_filter_price($_POST['market_price'][$key]),
                            );
                        }
                        else // 新增的规格
                        {
                            $specs[$key] = array(
                                'spec_1' => $spec_1,
                                'spec_2' => $spec_2,
                                'price' => $this->_filter_price($_POST['price'][$key]),
                                'stock' => intval($_POST['stock'][$key]),
                                'sku' => html_script(trim($_POST['sku'][$key])),
                                'base_price' => $this->_filter_price($_POST['floor_price'][$key]),
                                'market_price' => $this->_filter_price($_POST['market_price'][$key]),
                            );
                        }
                    }
                }
                break;
            default:
                break;
        }


        /* 分类 */
        $cates = array();
        $result = is_array($_POST['sgcate_id']) ? $_POST['sgcate_id'] : array();
        foreach ($result as $cate_id)
        {
            if (intval($cate_id) > 0)
            {
                $cates[$cate_id] = array(
                    'cate_id' => $cate_id,
                );
            }
        }

        /* 属性 */
        $attrs = array();
        $attr_list = isset($_POST['attr_value_list']) ? $_POST['attr_value_list'] : '';
        if ($attr_list)
        {
            foreach ($attr_list as $k => $arr)
            {
                if ($arr['attr_value'])
                {
                    if (is_array($arr['attr_value']))
                    {
                        foreach ($arr['attr_value'] as $key => $val)
                        {
                            $attrs[$k . '-' . $key]['attr_name'] = $arr['attr_name'];
                            $attrs[$k . '-' . $key]['attr_id'] = $k;
                            $attrs[$k . '-' . $key]['attr_value'] = html_script($val);
                            $attrs[$k . '-' . $key]['attr_uni'] = $this->_make_zh_to_num(html_script($val));
                        }
                    }
                    else
                    {
                        $attrs[$k]['attr_name'] = $arr['attr_name'];
                        $attrs[$k]['attr_id'] = $k;
                        $attrs[$k]['attr_value'] = html_script($arr['attr_value']);
                        $attrs[$k]['attr_uni'] = $this->_make_zh_to_num(html_script($arr['attr_value']));
                    }
                }
            }
            sort($attrs);
        }

        return array('goods' => $goods, 'specs' => $specs, 'cates' => $cates, 'goods_file_id' => $goods_file_id, 'desc_file_id' => $desc_file_id, 'attrs' => $attrs, 'price_arr' => $price_arr);
    }

    /**
     * 检查提交的数据
     */
    function _check_post_data($data, $id = 0)
    {
        /* if (!$this->_check_mgcate($data['goods']['cate_id']))
          {
          $this->_error('select_leaf_category');
          return;
          } */

        if (!$this->_goods_mod->unique(trim($data['goods']['goods_name']), $id))
        {
            $this->_error('name_exist');
            return false;
        }
        if ($data['goods']['spec_qty'] == 1 && empty($data['goods']['spec_name_1']) && empty($data['goods']['spec_name_2']) || $data['goods']['spec_qty'] == 2 && (empty($data['goods']['spec_name_1']) || empty($data['goods']['spec_name_2'])))
        {
            $this->_error('fill_spec_name');
            return false;
        }
        if (empty($data['specs']))
        {
            $this->_error('fill_spec');
            return false;
        }
        return true;
    }

    function _format_goods_tags($tags)
    {
        if (!$tags)
        {
            return '';
        }
        $tags = explode(',', str_replace(Lang::get('comma'), ',', $tags));
        array_walk($tags, create_function('&$item, $key', '$item=trim($item);'));
        $tags = array_filter($tags);
        $tmp = implode(',', $tags);
        if (strlen($tmp) > 100)
        {
            $tmp = sub_str($tmp, 100, false);
        }

        return ',' . $tmp . ',';
    }

    /**
     * 保存数据
     */
    function _save_post_data($data, $id = 0)
    {
        import('image.func');
        import('uploader.lib');
        import('img_server');

        /* if ($data['goods']['tags'])
          {
          $data['goods']['tags'] = $this->_format_goods_tags($data['goods']['tags']);
          } */

        if ($data['goods']['description'])
        {
            $data['goods']['description'] = conv_editor_img_to_image_server($data['goods']['description']);
        }

        /* 保存商品 */
        if ($id > 0)
        {
            if (!$this->_goods_mod->edit($id, $data['goods']))
            {
                $this->_error($this->_goods_mod->get_error());
                return false;
            }

            $goods_id = $id;
        }
        else
        {
            $goods_id = $this->_goods_mod->add($data['goods']);
            if (!$goods_id)
            {
                $this->_error($this->_goods_mod->get_error());
                return false;
            }
            if (($data['goods_file_id'] || $data['desc_file_id']))
            {
                $uploadfiles = array_merge($data['goods_file_id'], $data['desc_file_id']);
                $this->_uploadedfile_mod->edit(db_create_in($uploadfiles, 'file_id'), array('item_id' => $goods_id));
            }
            if (!empty($data['goods_file_id']))
            {
                $this->_image_mod->edit(db_create_in($data['goods_file_id'], 'file_id'), array('goods_id' => $goods_id));
            }
        }

        /* 保存规格 */
        if ($id > 0)
        {
            /* 删除的规格 */
            $goods_specs = $this->_goodsspec_mod->find(array(
                'conditions' => "goods_id = '{$id}'",
                'fields' => 'spec_id'
            ));
            $drop_spec_ids = array_diff(array_keys($goods_specs), array_keys($data['specs']));
            if (!empty($drop_spec_ids))
            {
                $this->_goodsspec_mod->drop($drop_spec_ids);
            }
            /* 删除的价格区间 */
            if ($data['goods']['price_type'] == 2)
            {
                $this->volumeprice_mod->delete($id);
            }
        }
        $default_spec = array(); // 初始化默认规格
        foreach ($data['specs'] as $key => $spec)
        {
            if ($spec_id = $spec['spec_id']) // 更新已有规格ID
            {
                $this->_goodsspec_mod->edit($spec_id, $spec);
            }
            else // 新加规格ID
            {
                $spec['goods_id'] = $goods_id;
                $spec_id = $this->_goodsspec_mod->add($spec);
            }
            if (empty($default_spec))
            {
                $default_spec = array('default_spec' => $spec_id);
            }
        }

        /* 更新默认规格 */
        $this->_goods_mod->edit($goods_id, $default_spec);
        if ($this->_goods_mod->has_error())
        {
            $this->_error($this->_goods_mod->get_error());
            return false;
        }

        //保存商品属性
        if ($data['attrs'])
        {
            foreach ($data['attrs'] as $key => $val)
            {
                $data['attrs'][$key]['goods_id'] = $goods_id;
            }
            if ($id > 0)
            {
                $this->attr_mod->update_data($data['attrs'], $goods_id, 'edit');
            }
            else
            {
                $this->attr_mod->update_data($data['attrs'], $goods_id, 'add');
            }
        }

        //报价方式为数量报价的时候保存商品价格区间
        if ($data['goods']['price_type'] == 1 && $data['price_arr'])
        {
            if ($id > 0)
            {
                /* 删除的价格区间 */
                $this->volumeprice_mod->delete($goods_id);
            }

            foreach ($data['price_arr'] as $key => $val)
            {
                $data['price_arr'][$key]['goods_id'] = $goods_id;
            }

            $this->volumeprice_mod->add($data['price_arr']);
        }

        /* 保存商品分类 */
        $this->_goods_mod->unlinkRelation('belongs_to_gcategory', $goods_id);
        if ($data['cates'])
        {
            $this->_goods_mod->createRelation('belongs_to_gcategory', $goods_id, $data['cates']);
        }

        /* 设置默认图片 */
        if (isset($data['goods_file_id'][0]))
        {
            $default_image = $this->_image_mod->get(array(
                'fields' => 'thumbnail',
                'conditions' => "goods_id = '$goods_id' AND file_id = '{$data[goods_file_id][0]}'",
            ));
            $this->_image_mod->edit("goods_id = $goods_id", array('sort_order' => 255));
            $this->_image_mod->edit("goods_id = $goods_id AND file_id = '{$data[goods_file_id][0]}'", array('sort_order' => 1));
            $this->_make_mobile_thumb_img($default_image ? $default_image['thumbnail'] : '', $goods_id);
        }

        $result = $this->_goods_mod->edit($goods_id, array(
            'default_image' => $default_image ? $default_image['thumbnail'] : '',
            'mobile_default_image' => $default_image ? get_image_server_url($this->_get_mobile_thumb_image($default_image['thumbnail'], $goods_id)) : '',
        ));

        return true;
    }

    //品牌申请列表
    function brand_list()
    {
        $_GET['store_id'] = $this->_store_id;
        $_GET['if_show'] = BRAND_PASSED;
        $con = array(
            array(
                'field' => 'store_id',
                'name' => 'store_id',
                'equal' => '=',
            ),
            array(
                'field' => 'if_show',
                'name' => 'if_show',
                'equal' => '=',
                'assoc' => 'or',
            ),);
        $filtered = '';
        if (!empty($_GET['brand_name']) || !empty($_GET['store']))
        {
            $_GET['brand_name'] && $filtered = " AND brand_name LIKE '%{$_GET['brand_name']}%'";
            $_GET['store'] && $filtered = $filtered . " AND store_id = " . $this->_store_id;
        }
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order, array('asc', 'desc')))
            {
                $sort = 'store_id';
                $order = 'desc';
            }
        }
        else
        {
            $sort = 'store_id';
            $order = 'desc';
        }
        $page = $this->_get_page(10);
        $conditions = $this->_get_query_conditions($con);
        $brand = $this->_brand_mod->find(array(
            'conditions' => "(1=1 $conditions)" . $filtered,
            'limit' => $page['limit'],
            'order' => "$sort $order",
            'count' => true,
        ));
        $page['item_count'] = $this->_brand_mod->getCount();
        $this->_format_page($page);
        $this->_curlocal(LANG::get('seller_center'), 'index.php?app=seller', LANG::get('my_goods'), 'index.php?app=my_goods', LANG::get('brand_list'));
        $this->_curitem('my_goods');
        $this->_curmenu('brand_apply_list');
        $this->import_resource(array(
            'script' => array(
                array(
                    'path' => 'jquery.plugins/jquery.validate.js',
                    'attr' => 'charset="utf-8"',
                ),
                array(
                    'path' => 'jquery.ui/jquery.ui.js',
                    'attr' => 'charset="utf-8"',
                ),
                array(
                    'attr' => 'id="dialog_js" charset="utf-8"',
                    'path' => 'dialog/dialog.js',
                ),
            ),
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css',
        ));
        $this->assign('page_info', $page);
        $this->assign('filtered', empty($filtered) ? 0 : 1);
        $this->assign('brands', $brand);
        $this->display('brand_list.html');
    }

    //品牌申请

    function brand_apply()
    {
        if (!IS_POST)
        {
            header("Content-Type:text/html;charset=" . CHARSET);
            $this->display('brand_apply.html');
        }
        else
        {
            $brand_name = trim($_POST['brand_name']);
            if (empty($brand_name))
            {
                $this->pop_warning("brand_name_required");
                exit;
            }

            if (!$this->_brand_mod->unique($brand_name))
            {
                $this->pop_warning('brand_name_exist');
                return;
            }
            if (!$brand_id = $this->_brand_mod->add(array('brand_name' => $brand_name, 'store_id' => $this->_store_id, 'if_show' => 0, 'tag' => trim($_POST['tag']))))  //获取brand_id
            {
                $this->pop_warning($this->_brand_mod->get_error());

                return;
            }

            $logo = $this->_upload_logo($brand_id);
            if ($logo === false)
            {
                return;
            }
            $this->_brand_mod->edit($brand_id, array('brand_logo' => $logo));
            $this->pop_warning('ok', 'my_goods_brand_apply', 'index.php?app=my_goods&act=brand_list');
        }
    }

    function brand_edit()
    {
        $id = intval($_GET['id']);
        $brand = $this->_brand_mod->find('store_id = ' . $this->_store_id . ' AND if_show = ' . BRAND_REFUSE . ' AND brand_id = ' . $id);
        $brand = current($brand);
        if (empty($brand))
        {
            $this->show_warning("not_rights");
            exit;
        }
        if (!IS_POST)
        {
            header("Content-Type:text/html;charset=" . CHARSET);
            $this->assign('brand', $brand);
            $this->display('brand_apply.html');
        }
        else
        {
            $brand_name = trim($_POST['brand_name']);
            if (!$this->_brand_mod->unique($brand_name, $id))
            {
                $this->pop_warning('brand_name_exist');
                return;
            }
            $data = array();
            if (isset($_FILES['brand_logo']))
            {
                $logo = $this->_upload_logo($id);
                if ($logo === false)
                {
                    return;
                }
                $data['brand_logo'] = $logo;
            }
            $data['brand_name'] = $brand_name;
            $data['tag'] = trim($_POST['tag']);
            $this->_brand_mod->edit($id, $data);
            if ($this->_brand_mod->has_error())
            {
                $this->pop_warning($this->_brand_mod->get_error());
                exit;
            }
            $this->pop_warning('ok', 'my_goods_brand_edit');
        }
    }

    function brand_drop()
    {
        $id = intval($_GET['id']);
        if (empty($id))
        {
            $this->show_warning('request_error');
            exit;
        }
        $brand = $this->_brand_mod->find("store_id = " . $this->_store_id . " AND if_show = " . BRAND_REFUSE . " AND brand_id = " . $id);
        $brand = current($brand);
        if (empty($brand))
        {
            $this->show_warning('request_error');
            exit;
        }
        if (!$this->_brand_mod->drop($id))
        {
            $this->show_warning($this->_brand_mod->get_error());
            exit;
        }
        if (!empty($brand['brand_logo']) && file_exists(ROOT_PATH . '/' . $brand['brand_logo']))
        {
            @unlink(ROOT_PATH . '/' . $brand['brand_logo']);
        }
        $this->show_message('drop_brand_ok', 'back_list', 'index.php?app=my_goods&act=brand_list');
    }

    function check_brand()
    {
        $brand_name = $_GET['brand_name'];
        if (!$brand_name)
        {
            echo ecm_json_encode(true);
            return;
        }
        if ($this->_brand_mod->unique($brand_name))
        {
            echo ecm_json_encode(true);
        }
        else
        {
            echo ecm_json_encode(false);
        }
        return;
    }

    function _upload_logo($brand_id)
    {
        $file = $_FILES['brand_logo'];
        if ($file['error'] == UPLOAD_ERR_NO_FILE || !isset($_FILES['brand_logo'])) // 没有文件被上传
        {
            return '';
        }
        import('uploader.lib');             //导入上传类
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE); //限制文件类型
        $uploader->addFile($_FILES['brand_logo']); //上传logo
        if (!$uploader->file_info())
        {
            $this->pop_warning($uploader->get_error());
            if (ACT == 'brand_apply')
            {
                $m_brand = &m('brand');
                $m_brand->drop($brand_id);
            }
            return false;
        }
        /* 指定保存位置的根目录 */
        $uploader->root_dir(ROOT_PATH);

        /* 上传 */
        if ($file_path = $uploader->save('data/files/mall/brand', $brand_id))   //保存到指定目录，并以指定文件名$brand_id存储
        {
            return $file_path;
        }
        else
        {
            return false;
        }
    }

    /* 价格过滤，返回非负浮点数 */

    function _filter_price($price)
    {
        return abs(floatval($price));
    }

    /* 取得可以作为上级的商品分类数据 */

    function _get_options($except = NULL)
    {
        $gcategories = $this->_gcategory_mod->get_list();
        $tree = & $this->_tree($gcategories);

        return $tree->getOptions(MAX_LAYER - 1, 0, $except);
    }

    /**
     * 获取运费模板类型
     */
    function get_shipping_type()
    {
        $pid = isset($_GET['pid']) ? intval($_GET['pid']) : '';
        if ($pid)
        {
            $shipping_mod = & m('shipping');
            $data = $shipping_mod->get_info($pid); //vdump($data);
            echo ecm_json_encode($data);
        }
    }

    /**
     * 用于本类调用，生成缩略图
     */
    function _make_mobile_thumb_img($file_path, $goodsId = 0, $storeId = 0)
    {
        if (!$storeId)
            $storeId = $this->_get_store_id_by_image_url($file_path);
        if ($goodsId && $storeId && $file_path)
        {
            import('image.func');
            $mobileThumbnail = $this->_get_mobile_thumb_image($file_path, $goodsId, $storeId);
            make_thumb(ROOT_PATH . '/' . remove_image_server_host($file_path), ROOT_PATH . '/' . $mobileThumbnail, MOBILE_THUMB_WIDTH, MOBILE_THUMB_HEIGHT, THUMB_QUALITY);
        }
    }

    /**
     * 用于本类调用,根据规则获取手机缩略图
     */
    function _get_mobile_thumb_image($file_path, $goodsId = 0, $storeId = 0)
    {
        $result = $file_path;
        if (!$storeId)
            $storeId = $this->_get_store_id_by_image_url($file_path);
        $result = 'data/files/store_' . $storeId . '/mobile/small_' . $goodsId . MOBILE_THUMB_WIDTH . MOBILE_THUMB_HEIGHT . "." . get_file_extension($file_path);
        return $result;
    }

    /**
     * 用于本类调用,根据图片路径获取store_id
     */
    function _get_store_id_by_image_url($file_path)
    {
        $pattern = '#(.*?)store_([\d+]+)\/(.*?)#i';
        preg_match_all($pattern, $file_path, $matches);
        return isset($matches[2]) ? $matches[2][0] : 0;
    }

    /**
     *  获取某个分类的属性,返回HTML字符串
     *  @author  yanghj 2014.07.23
     *  @param int $cate_id    商品分类ID
     *  @param int $goods_id   商品ID
     *  @return str
     */
    function _get_html_attribute($cate_id, $goods_id = 0)
    {
        $str = '';
        $temp_arr = array();
        $attr_data = $this->_attribute_mod->find(array(
            'fields' => 'attr_id,attr_name,attr_input_type,attr_values',
            'conditions' => " cate_id = " . $cate_id,
            'order' => 'sort_order ASC',
            )
        );
        if ($goods_id > 0)
        {
            $gattr = $this->attr_mod->get_infos($goods_id);
        }
        if ($gattr)
        {
            foreach ($gattr as $key => $val)
            {
                $temp_arr[$val['attr_id']][$val['attr_value']]['attr_id'] = $val['attr_id'];
                $temp_arr[$val['attr_id']][$val['attr_value']]['attr_value'] = $val['attr_value'];
            }
        }
        if ($attr_data)
        {
            $str .= '<table class="goods-p-table">';
            foreach ($attr_data as $k => $attr)
            {
                switch (intval($attr['attr_input_type']))
                {
                    case 0: // 手工录入
                        if (isset($temp_arr[$attr['attr_id']]))
                        {
                            $value = array_keys($temp_arr[$attr['attr_id']]);
                        }
                        $str .='<tr><td width="100" align="right">' . $attr['attr_name'] . '：</td><td><input type="hidden" value="' . $attr['attr_name'] . '" name="attr_value_list[' . $attr['attr_id'] . '][attr_name]" /><input type="text" value="' . $value[0] . '" name="attr_value_list[' . $attr['attr_id'] . '][attr_value]" /></td></tr>';
                        break;
                    case 1: // 单选属性
                        $attr_values = attr_to_array($attr['attr_values']);
                        $str .='<tr><td width="100" align="right">' . $attr['attr_name'] . '：</td><td><input type="hidden" value="' . $attr['attr_name'] . '" name="attr_value_list[' . $attr['attr_id'] . '][attr_name]" />';
                        foreach ($attr_values as $k => $values)
                        {
                            $str .='<input type="radio" value="' . $values . '"';
                            if (isset($temp_arr[$attr['attr_id']][$values]))
                            {
                                $str .=' checked ';
                            }
                            $str .='name="attr_value_list[' . $attr['attr_id'] . '][attr_value][]"><label for="attr_value_' . $attr['attr_id'] . '_' . $k . '">' . $values . '</label>&nbsp;';
                        }
                        $str .='</td></tr>';
                        break;
                    case 2: // 复选属性
                        $attr_values = attr_to_array($attr['attr_values']);
                        $str .='<tr><td width="100" align="right">' . $attr['attr_name'] . '：</td><td><input type="hidden" value="' . $attr['attr_name'] . '" name="attr_value_list[' . $attr['attr_id'] . '][attr_name]" />';
                        foreach ($attr_values as $k => $values)
                        {
                            $str .='<input id="attr_value_' . $attr['attr_id'] . '_' . $k . '" type="checkbox" value="' . $values . '"';
                            if (isset($temp_arr[$attr['attr_id']][$values]))
                            {
                                $str .=' checked ';
                            }
                            $str .='name="attr_value_list[' . $attr['attr_id'] . '][attr_value][]"><label for="attr_value_' . $attr['attr_id'] . '_' . $k . '">' . $values . '</label>&nbsp;';
                        }
                        $str .='</td></tr>';
                        break;
                    case 3: // 列表属性
                        $attr_values = attr_to_array($attr['attr_values']);
                        $str .='<tr><td width="100" align="right">' . $attr['attr_name'] . '：</td><td><input type="hidden" value="' . $attr['attr_name'] . '" name="attr_value_list[' . $attr['attr_id'] . '][attr_name]" /><select name="attr_value_list[' . $attr['attr_id'] . '][attr_value]"><option value="">请选择</option>';
                        foreach ($attr_values as $k => $values)
                        {
                            $str .='<option value="' . $values . '"';
                            if (isset($temp_arr[$attr['attr_id']][$values]))
                            {
                                $str .=' selected ';
                            }
                            $str .= '>' . $values . '</option>';
                        }
                        $str .='</select></td></tr>';
                        break;
                    case 4: // 多行文本框
                        if (isset($temp_arr[$attr['attr_id']]))
                        {
                            $value = array_keys($temp_arr[$attr['attr_id']]);
                        }
                        $str .='<tr><td width="100" align="right">' . $attr['attr_name'] . '：</td><td><textarea name="attr_value_list[' . $attr['attr_id'] . '][attr_value]" clos="20" rows="3">' . $value[0] . '</textarea></td></tr>';
                        break;
                }
            }
            $str .= '</table>';
        }
        return $str;
    }

    /**
     *  获取某个分类的规格,返回HTML字符串
     *  @author  yanghj 2014.07.23
     *  @param int $cate_id    商品分类ID
     *  @param int $goods_id   商品ID
     *  @return str
     */
    function _get_html_spec($cate_id, $goods_id = 0)
    {
        $str = '';
        $goods_spec['spec_1'] = array();
        $goods_spec['spec_2'] = array();
        $temp = array();
        $spec_diff = array();
        $spec_data = $this->spec_mod->find(array(
            'fields' => 'spec_id,spec_name,spec_values',
            'conditions' => " cate_id = " . $cate_id,
            'order' => 'spec_id ASC',
            )
        );
        if ($goods_id > 0)
        {
            $gspec = $this->_goodsspec_mod->find(array(
                'fields' => 'spec_1,spec_2',
                'conditions' => " (spec_1 !='' OR spec_2 !='') AND goods_id = " . $goods_id,
                )
            );
        }
        if ($gspec)
        {
            foreach ($gspec as $key => $val)
            {
                $goods_spec['spec_1'][] = $val['spec_1'];
                $goods_spec['spec_2'][] = $val['spec_2'];
            }
            $goods_spec['spec_1'] = array_unique($goods_spec['spec_1']);
            $goods_spec['spec_2'] = array_unique($goods_spec['spec_2']);
        }
        if ($spec_data)
        {
            sort($spec_data);
            foreach ($spec_data as $key => $spec)
            {
                if(empty($spec['spec_values']))
                {
                    continue;
                }
                $spec_values = attr_to_array($spec['spec_values']);

                $str .='<dl class="goods-f-c f-cb" name="goodsdlone"><dt><em><input type="hidden" name="spec_name_' . ($key + 1) . '" value="' . $spec['spec_name'] . '">' . $spec['spec_name'] . '：</em></dt><dd><ul class="f-cb">';
                foreach ($spec_values as $k => $values)
                {

                    $str .='<li><input id="spec_id_' . $spec['spec_id'] . '_' . $k . '" type="checkbox" value="' . $values . '"';
                    if (in_array($values, $goods_spec['spec_' . ($key + 1)]))
                    {
                        $str .=' checked ';
                        $temp[$k] = $values;
                    }
                    $str .='><label for="spec_id_' . $spec['spec_id'] . '_' . $k . '">' . $values . '</label></li>&nbsp;';
                }
                $spec_diff = array_diff($goods_spec['spec_' . ($key + 1)], $temp);
                if ($spec_diff)
                {
                    foreach ($spec_diff as $ks => $diff)
                    {
                        if ($diff)
                        {
                            $str .='<li><input id="spec_id_' . $spec['spec_id'] . '_' . $ks . '_' . $ks . '" type="checkbox" value="' . $diff . '" checked ><label for="spec_id_' . $spec['spec_id'] . '_' . $ks . '_' . $ks . '">' . $diff . '</label></li>&nbsp;';
                        }
                    }
                }
                $str .='<li><input onclick="wl.stopBubble(event)" type="text" id="diyspec' . ($key + 1) . '" class="diyspec-width" /><a href="javascript:void(0)" class="g-p-btn" onclick="addSpec(' . ($key + 1) . ')">增加</a></li>';
                $str .='</ul></dd></dl>';
            }
        }
        return $str;
    }

    function _make_zh_to_num($zh)
    {
        $array = array(
            'a' => 10, 'b' => 11,'c' => 12, 'd' => 13,'e' => 14, 'f' => 15,'g' => 16, 'h' => 17,
            'i' => 18, 'j' => 19,'k' => 20, 'l' => 21,'m' => 22, 'n' => 23,'o' => 24, 'p' => 25,
            'q' => 26, 'r' => 27,'s' => 28, 't' => 29,'u' => 30, 'v' => 31,'w' => 32, 'x' => 33,
            'y' => 34, 'z' => 35
        );
        $result = "";
        $md5 = md5($zh);
        $uni = substr($md5, 0, 2) .substr($md5, -3, 3);
        for($i = 0; $i<  strlen($uni) ; $i++){
            if($uni{$i} && !intval($uni{$i})){
                $result .= $array[$uni{$i}];
            }else{
                $result .= $uni{$i};
            }
        }

        return $result;
    }

}

?>
